package com.edu.admin.controller;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.validation.Valid;

import org.apache.commons.collections.MapUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import com.edu.admin.entity.SysUser;
import com.edu.admin.enums.ExceptionEnum;
import com.edu.admin.enums.UseTypeEnum;
import com.edu.admin.service.SchoolService;
import com.edu.admin.service.UserService;
import com.edu.admin.common.RestResult;
import com.edu.admin.vo.UserVo;
import com.github.pagehelper.PageInfo;

/**
 * 教师管理
 *  
 * @author Wangjiong
 * 
 */
@RestController
@RequestMapping(value = "/teacher", name = "教师管理")
public class TeacherController {

	@Autowired
	private UserService	userService;
	@Autowired
	private SchoolService	schoolService;
	
	/**
     * 获取教师列表
     * 
	 * @apiGroup teacher
	 * @api {get} /teacher/listAllTeacherPage 获取教师列表
	 * @apiVersion 1.0.0
	 * @apiName getAllTecacherListBySchoolName
	 *
	 * @apiParam {String} schoolName 学校名称  required = false
	 * @apiParam {String} userName 教师姓名  required = false
	 * @apiParam {String} account 教师账号  required = false
	 * @apiParam {Integer} pageNum 页码  required = false
	 * @apiParam {Integer} pageSize 每页记录数  required = false
	 * 
	 *
	 * @apiSuccessExample Success-Response:
	 * HTTP/1.1 200
		{
		    "code": 200,
		    "msg": "success",
		    "data": {
		        "total": 2,
		        "list": [
		            {
		                "userId": 11,
		                "account": "13681234567",
		                "userName": "123",
		                "pinyin": null,
		                "phone": "13681234567",
		                "phaseId": 2,
		                "schoolId": 1,
		                "classesId": null,
		                "birthday": null,
		                "gender": "0",
		                "type": 1,
		                "imageUrl": null,
		                "provinceCode": "110000",
		                "cityCode": "110100",
		                "districtCode": "110105",
		                "address": null,
		                "roleId": 6,
		                "intro": null,
		                "studentNo": null,
		                "teacherNo": "",
		                "openid": null,
		                "point": null,
		                "userRemark": null,
		                "useType": 0,
		                "schoolName": "测试学校",
		                "classesName": null,
		                "gradeId": null,
		                "gradeName": null,
		                "phaseName": "初中",
		                "provinceName": "北京市",
		                "cityName": "市辖区",
		                "districtName": "朝阳区",
		                "subjects": [
		                    7
		                ],
		                "roleName": "教师"
		            },
		            {
		                "userId": 14,
		                "account": "13681234553",
		                "userName": "55555",
		                "pinyin": null,
		                "phone": "13681234553",
		                "phaseId": 2,
		                "schoolId": 1,
		                "classesId": null,
		                "birthday": null,
		                "gender": "0",
		                "type": 1,
		                "imageUrl": null,
		                "provinceCode": "110000",
		                "cityCode": "110100",
		                "districtCode": "110105",
		                "address": null,
		                "roleId": 6,
		                "intro": null,
		                "studentNo": null,
		                "teacherNo": "",
		                "openid": null,
		                "point": null,
		                "userRemark": null,
		                "useType": 0,
		                "schoolName": "测试学校",
		                "classesName": null,
		                "gradeId": null,
		                "gradeName": null,
		                "phaseName": "初中",
		                "provinceName": "北京市",
		                "cityName": "市辖区",
		                "districtName": "朝阳区",
		                "subjects": [
		                    5
		                ],
		                "roleName": "教师"
		            }
		        ],
		        "pageNum": 1,
		        "pageSize": 10,
		        "size": 2,
		        "startRow": 1,
		        "endRow": 2,
		        "pages": 1,
		        "prePage": 0,
		        "nextPage": 0,
		        "isFirstPage": true,
		        "isLastPage": true,
		        "hasPreviousPage": false,
		        "hasNextPage": false,
		        "navigatePages": 8,
		        "navigatepageNums": [
		            1
		        ],
		        "navigateFirstPage": 1,
		        "navigateLastPage": 1,
		        "firstPage": 1,
		        "lastPage": 1
		    }
		}
	 *
	 *
	 */
    @RequestMapping(value = "listAllTeacherPage", name = "教师列表", method = RequestMethod.GET)
    @PreAuthorize("hasAuthority('/teacher/listAllTeacherPage')")
    public RestResult getAllTecacherListBySchoolName(@RequestParam(name = "schoolName", required = false) String schoolName,
    		@RequestParam(name = "userName", required = false) String userName,
    		@RequestParam(name = "account", required = false) String account,
    		@RequestParam(name = "pageNum", required = false) Integer pageNum,
			@RequestParam(name = "pageSize", required = false) Integer pageSize)
    		throws Exception {
    	
    	PageInfo<UserVo> pageInfo = userService.getAllTeacherListBySchoolName(pageNum, pageSize,schoolName, userName, account,null);
        
        return RestResult.ok(pageInfo);
    }
    
    /**
     * 获取学校教师列表
     * 
	 * @apiGroup teacher
	 * @api {get} /teacher/listAllSchoolTeacherPage 获取学校教师列表
	 * @apiVersion 1.0.0
	 * @apiName getAllTecacherListPageBySchoolId
	 *
	 * @apiParam {Long} schoolId 学校id  required = false
	 * @apiParam {String} userName 教师姓名  required = false
	 * @apiParam {String} account 教师账号  required = false
	 * @apiParam {Integer} pageNum 页码  required = false
	 * @apiParam {Integer} pageSize 每页记录数  required = false
	 * 
	 *
	 * @apiSuccessExample Success-Response:
	 * HTTP/1.1 200
		{
		    "code": 200,
		    "msg": "success",
		    "data": {
		        "total": 2,
		        "list": [
		            {
		                "userId": 11,
		                "account": "13681234567",
		                "userName": "123",
		                "pinyin": null,
		                "phone": "13681234567",
		                "phaseId": 2,
		                "schoolId": 1,
		                "classesId": null,
		                "birthday": null,
		                "gender": "0",
		                "type": 1,
		                "imageUrl": null,
		                "provinceCode": "110000",
		                "cityCode": "110100",
		                "districtCode": "110105",
		                "address": null,
		                "roleId": 6,
		                "intro": null,
		                "studentNo": null,
		                "teacherNo": "",
		                "openid": null,
		                "point": null,
		                "userRemark": null,
		                "useType": 0,
		                "schoolName": "测试学校",
		                "classesName": null,
		                "gradeId": null,
		                "gradeName": null,
		                "phaseName": "初中",
		                "provinceName": "北京市",
		                "cityName": "市辖区",
		                "districtName": "朝阳区",
		                "subjects": [
		                    7
		                ],
		                "roleName": "教师"
		            },
		            {
		                "userId": 14,
		                "account": "13681234553",
		                "userName": "55555",
		                "pinyin": null,
		                "phone": "13681234553",
		                "phaseId": 2,
		                "schoolId": 1,
		                "classesId": null,
		                "birthday": null,
		                "gender": "0",
		                "type": 1,
		                "imageUrl": null,
		                "provinceCode": "110000",
		                "cityCode": "110100",
		                "districtCode": "110105",
		                "address": null,
		                "roleId": 6,
		                "intro": null,
		                "studentNo": null,
		                "teacherNo": "",
		                "openid": null,
		                "point": null,
		                "userRemark": null,
		                "useType": 0,
		                "schoolName": "测试学校",
		                "classesName": null,
		                "gradeId": null,
		                "gradeName": null,
		                "phaseName": "初中",
		                "provinceName": "北京市",
		                "cityName": "市辖区",
		                "districtName": "朝阳区",
		                "subjects": [
		                    5
		                ],
		                "roleName": "教师"
		            }
		        ],
		        "pageNum": 1,
		        "pageSize": 10,
		        "size": 2,
		        "startRow": 1,
		        "endRow": 2,
		        "pages": 1,
		        "prePage": 0,
		        "nextPage": 0,
		        "isFirstPage": true,
		        "isLastPage": true,
		        "hasPreviousPage": false,
		        "hasNextPage": false,
		        "navigatePages": 8,
		        "navigatepageNums": [
		            1
		        ],
		        "navigateFirstPage": 1,
		        "navigateLastPage": 1,
		        "firstPage": 1,
		        "lastPage": 1
		    }
		}
	 *
	 *
	 */
    @RequestMapping(value = "listAllSchoolTeacherPage", name = "教师列表", method = RequestMethod.GET)
    @PreAuthorize("hasAuthority('/teacher/listAllSchoolTeacherPage')")
    public RestResult getAllTecacherListPageBySchoolId(@RequestParam(name = "schoolId") Long schoolId,
													@RequestParam(name = "userName", required = false) String userName,
													@RequestParam(name = "account", required = false) String account,
													@RequestParam(name = "pageNum", required = false) Integer pageNum,
													@RequestParam(name = "pageSize", required = false) Integer pageSize)
													throws Exception {
    	
    	PageInfo<UserVo> pageInfo = userService.getAllTeacherListPageBySchoolId(pageNum, pageSize,schoolId, userName,account,null);
        
        return RestResult.ok(pageInfo);
    }
    
    
    /**
     * 查询学科教师列表
     * 
	 * @apiGroup teacher
	 * @api {get} /teacher/listSchoolTeacherBySubjectId 查询学科教师列表
	 * @apiVersion 1.0.0
	 * @apiName findSchoolTecacherListBySubjectId
	 *
	 * @apiParam {Long} schoolId 学校id  required = false
	 * @apiParam {String} userName 教师姓名  required = false
	 * @apiParam {String} account 教师账号  required = false
	 * @apiParam {Integer} pageNum 页码  required = false
	 * @apiParam {Integer} pageSize 每页记录数  required = false
	 * 
	 *
	 * @apiSuccessExample Success-Response:
	 * HTTP/1.1 200
		
	 *
	 *
	 */
    @RequestMapping(value = "listSchoolTeacherBySubjectId", name = "查询学科教师列表", method = RequestMethod.GET)
    @PreAuthorize("hasAuthority('/teacher/listSchoolTeacherBySubjectId')")
    public RestResult findSchoolTecacherListBySubjectId(@RequestParam(name = "schoolId") Long schoolId,
    												@RequestParam(name = "phaseId", required = false) Long phaseId,
    												@RequestParam(name = "subjectId", required = false) Long subjectId,
													@RequestParam(name = "userName", required = false) String userName)
													throws Exception {
    	
    	List<UserVo> userList = userService.findTeacherListBySubjectId(schoolId, phaseId, subjectId, userName);
        
        return RestResult.ok(userList);
    }
    
    /**
	 * 保存教师信息
	 *
	 * @apiGroup teacher
	 * @api {post} /teacher/save 保存教师信息
	 * @apiVersion 1.0.0
	 * @apiName save
	 *
	 * @apiParam {SysUser} teacher 教师信息
	 * @apiParamExample 请求示例（json）
	  * {
		    "userName": "张三",
		    "teacherNo": "3454463",
		    "phone": "13301234567",
		    "gender": 1,
		    "schoolId": 1,
		    "phaseId": 2,
		    "roleId": 1,
		    "type": 2,
		    "subjects": [4,5]
		
		}
	 *
	 * @apiSuccessExample Success-Response:
	 * HTTP/1.1 200
		{
		    "code": 200,
		    "msg": "success",
		    "data": {
		        "userId": 3
		    }
		}
	 *
	 *
	 */
	@RequestMapping(value = "save", name = "保存教师信息", method = RequestMethod.POST)
	@PreAuthorize("hasAuthority('/teacher/save')")
	public RestResult save(@Valid @RequestBody SysUser teacher) throws Exception{
		Map<String, Object> result = new HashMap<>();
		
		result = userService.saveTeacher(teacher);
		
		schoolService.updateSchoolTeacherNumBySchoolId(teacher.getSchoolId());
		
		return RestResult.ok(result);
	}
	
	/**
	 * 批量启用或停用
	 *
	 * @apiGroup teacher
	 * @api {post} /teacher/batchuse 批量启用或停用
	 * @apiVersion 1.0.0
	 * @apiName batchUse
	 *
	 * @apiParam {Map} dataMap 启用 {"use": 0}  停用 {"use": 1}
	 * @apiParamExample 请求示例（json）
	 * {
		    "teacherIds": [2,3,5],
		    "use": 1 
		
		}
	 *
	 * @apiSuccessExample Success-Response:
	 * HTTP/1.1 200
		{
		    "code": 200,
		    "msg": "success",
		    "data": null
		}
	 *
	 *
	 */
	@RequestMapping(value = "/batchuse", name = "批量启用或停用", method = RequestMethod.POST)
	@PreAuthorize("hasAuthority('/teacher/batchuse')")
	public RestResult batchUse(@RequestBody Map<String,Object> dataMap) throws Exception{
		
		Integer isUse = MapUtils.getInteger(dataMap,"use");
        @SuppressWarnings("unchecked")
		List<String> teacherIdList = (List<String>)MapUtils.getObject(dataMap,"teacherIds");
        Long[] idList = new Long[]{};
        if(teacherIdList != null){
        	idList = new Long[teacherIdList.size()];
        	int i = 0 ;
            for (String sId:teacherIdList)
            {
            	idList[i]= Long.valueOf(sId);
            	i++;
            }
        }

        userService.batchUse(idList, isUse);
		
		return RestResult.ok();
		
	}
	
	/**
     * 启用教师
     * 
	 * @apiGroup teacher
	 * @api {post} /teacher/on 启用教师
	 * @apiVersion 1.0.0
	 * @apiName onTeacher
	 *
	 * @apiParam {Map} dataMap 
	 * @apiParamExample 请求示例（json）
	 * {
		    "userId": 2
		}
	 *
	 * @apiSuccessExample Success-Response:
	 * HTTP/1.1 200
		{
		    "code": 200,
		    "msg": "success",
		    "data": 1
		}
	 *
	 *
	 */
    @RequestMapping(value = "/on", name = "启用教师",  method = RequestMethod.POST)
    @PreAuthorize("hasAuthority('/teacher/on')")
    public RestResult onTeacher(@RequestBody Map<String,Object> dataMap) throws Exception {
    	
    	Long userId = MapUtils.getLong(dataMap,"userId");
    	if (userId == null || userId<=0)
    	{
    		return RestResult.error(ExceptionEnum.BADREQUEST.getCode(),ExceptionEnum.BADREQUEST.getMsg());
    	}
    	
    	int isOk = userService.useUser(userId,UseTypeEnum.ISUSE.getCode());
    	if (isOk>0)
		{
			return RestResult.ok(isOk);
		}
		else
		{
			return RestResult.error();
		}
    }
    
    /**
     * 停用教师
     * 
     * @apiGroup teacher
	 * @api {post} /teacher/off 停用教师
	 * @apiVersion 1.0.0
	 * @apiName offTeacher
	 *
	 * @apiParam {Map} dataMap 
	 * @apiParamExample 请求示例（json）
	 * {
		    "userId": 2
		}
	 *
	 * @apiSuccessExample Success-Response:
	 * HTTP/1.1 200
		{
		    "code": 200,
		    "msg": "success",
		    "data": 1
		}
	 *
	 *
	 */
    @RequestMapping(value = "/off", name = "停用教师",  method = RequestMethod.POST)
    @PreAuthorize("hasAuthority('/teacher/off')")
    public RestResult offTeacher(@RequestBody Map<String,Object> dataMap) throws Exception {
    	
    	Long userId = MapUtils.getLong(dataMap,"userId");
    	if (userId == null || userId<=0)
    	{
    		return RestResult.error(ExceptionEnum.BADREQUEST.getCode(),ExceptionEnum.BADREQUEST.getMsg());
    	}
    	
    	int isOk = userService.useUser(userId,UseTypeEnum.NOTUSE.getCode());
    	if (isOk>0)
		{
			return RestResult.ok(isOk);
		}
		else
		{
			return RestResult.error();
		}
    }
	
	/**
	 * 获取教师信息
	 * 
	 * @apiGroup teacher
	 * @api {get} /teacher/info 获取教师信息
	 * @apiVersion 1.0.0
	 * @apiName getTecacher
	 *
	 * @apiParam {Long} userId 用户id
	 * 
	 *
	 * @apiSuccessExample Success-Response:
	 * HTTP/1.1 200
		{
		    "code": 200,
		    "msg": "success",
		    "data": {
		        "userId": 7,
		        "account": "13691234567",
		        "userName": "赵六",
		        "pinyin": null,
		        "phone": "13691234567",
		        "phaseId": 3,
		        "schoolId": 3,
		        "classesId": null,
		        "birthday": null,
		        "gender": "0",
		        "type": 1,
		        "imageUrl": null,
		        "provinceCode": "110000",
		        "cityCode": "110100",
		        "districtCode": "110101",
		        "address": null,
		        "roleId": 5,
		        "intro": null,
		        "studentNo": null,
		        "teacherNo": "",
		        "openid": null,
		        "point": null,
		        "userRemark": null,
		        "useType": 0,
		        "schoolName": "测试学校3",
		        "classesName": null,
		        "gradeId": null,
		        "gradeName": null,
		        "phaseName": "高中",
		        "provinceName": "北京市",
		        "cityName": "市辖区",
		        "districtName": "东城区",
		        "subjects": null,
		        "roleName": "教师"
		    }
		}
	 *
	 *
	 */
	@RequestMapping(value = "info", name = "教师信息", method = RequestMethod.GET)
	@PreAuthorize("hasAuthority('/teacher/info')")
	public RestResult getTecacher(@RequestParam Long userId) throws Exception{
		UserVo teacherVo = null;
		
		teacherVo = userService.getUserById(userId);
		
		return RestResult.ok(teacherVo);
	}
	
	/**
     * 重置密码
     * 
     * @apiGroup teacher
	 * @api {post} /teacher/resetpassword 重置密码
	 * @apiVersion 1.0.0
	 * @apiName resetTecacherPassword
	 *
	 * @apiParam {Map} dataMap 
	 * @apiParamExample 请求示例（json）
	 * {
		    "userId": 2
		}
	 *
	 *
	 * @apiSuccessExample Success-Response:
	 * HTTP/1.1 200
		{
		    "code": 200,
		    "msg": "success",
		    "data": 1
		}
	 *
	 *
	 */
    @RequestMapping(value="/resetpassword" , method = RequestMethod.POST)
    @PreAuthorize("hasAuthority('/teacher/resetpassword')")
    public RestResult resetTecacherPassword(@RequestBody Map<String,Object> dataMap) throws Exception {
 	   
    	Long userId = MapUtils.getLong(dataMap, "userId");
    	
    	if (userId == null || userId<=0 )
    	{
    		return RestResult.error(ExceptionEnum.BADREQUEST.getCode(),ExceptionEnum.BADREQUEST.getMsg());
    	}
    			
    	int isOk = userService.restUserPassword(userId);
    	if (isOk>0)
		{
			return RestResult.ok(isOk);
		}
		else
		{
			return RestResult.error();
		}
    }
    
    /**
	 *
	 * @apiGroup teacher
	 * @api {post} /teacher/delete 删除教师
	 * @apiVersion 1.0.0
	 * @apiName deleteTeacher
	 *
	 * @apiParam {Map} dataMap 
	 * @apiParamExample 请求示例（json）
	 * {
		    "userId": 2,
		    "schoolId": 1
		}
	 *
	 * @apiSuccessExample Success-Response:
	 * HTTP/1.1 200
		{
		    "code": 200,
		    "msg": "success",
		    "data": 1
		}
	 *
	 *
	 */
   @RequestMapping(value="/delete" , method = RequestMethod.POST)
   @PreAuthorize("hasAuthority('/teacher/delete')")
   public RestResult deleteUser(@RequestBody Map<String,Object> dataMap) throws Exception {
	   
	Long userId = MapUtils.getLong(dataMap, "userId");
	Long schoolId = MapUtils.getLong(dataMap, "schoolId");
	
	if (userId == null || userId<=0 || schoolId == null || schoolId<=0 )
	{
		return RestResult.error(ExceptionEnum.BADREQUEST.getCode(),ExceptionEnum.BADREQUEST.getMsg());
	}
	
	   
   	int isOk = userService.deleteUser(userId);
   	if (isOk>0)
		{
   			schoolService.updateSchoolTeacherNumBySchoolId(schoolId);
   		
			return RestResult.ok(isOk);
		}
		else
		{
			return RestResult.error();
		}
   }
    
    /**
     * 教师转校
     *  
	 * @apiGroup teacher
	 * @api {post} /teacher/move 教师转校或转班
	 * @apiVersion 1.0.0
	 * @apiName teacherMove
	 *
	 * @apiParam {Map} dataMap 
	 * @apiParamExample 请求示例（json）
	 * {
		    "teacherIds": [2,3,5],
		    "schoolId": 1,
		}
	 *
	 * @apiSuccessExample Success-Response:
	 * HTTP/1.1 200
		{
		    "code": 200,
		    "msg": "success",
		    "data": null
		}
	 *
	 *
	 */
    @RequestMapping(value = "/move",method = RequestMethod.POST)
    @PreAuthorize("hasAuthority('/teacher/move')")
    public RestResult teacherMove(@RequestBody Map<String,Object> dataMap) throws Exception {
    	
    	Long schoolId = MapUtils.getLong(dataMap, "schoolId");
    	String teacherIds = (String)MapUtils.getObject(dataMap,"teacherIds");
    	String[] tids = teacherIds.split(",");
    	Long[] ids = new Long[tids.length];
    		
	    for(int i=0;i<tids.length;i++){

	    	ids[i] = Long.parseLong(tids[i]);

	    }
        userService.moveTeachers(ids, schoolId);
        
        schoolService.updateSchoolTeacherNum();
        
        return RestResult.ok();
    }

    /**
     * 学校教师移出校
     * 
     * @apiGroup teacher
	 * @api {post} /teacher/outschool 学校教师移出校
	 * @apiVersion 1.0.0
	 * @apiName outSchool
	 *
	 * @apiParam {Map} dataMap 
	 * @apiParamExample 请求示例（json）
	 * {
		    "teacherIds": [2,3,5],
		    "schoolId": 1
		}
	 *
	 * @apiSuccessExample Success-Response:
	 * HTTP/1.1 200
		{
		    "code": 200,
		    "msg": "success",
		    "data": {
		        "statusinfo": "success"
		    }
		}
	 *
	 *
	 */
    @RequestMapping(value = "/outschool",method = RequestMethod.POST)
    @PreAuthorize("hasAuthority('/teacher/outschool')")
    public RestResult outSchool(@RequestBody Map<String,Object> dataMap) throws Exception {
    	
    	Long schoolId = MapUtils.getLong(dataMap, "schoolId");
    	String teacherIds = (String)MapUtils.getObject(dataMap,"teacherIds");
    	String[] tids = teacherIds.split(",");
    	Long[] ids = new Long[tids.length];
    		
	    for(int i=0;i<tids.length;i++){

	    	ids[i] = Long.parseLong(tids[i]);

	    }
	    
        userService.outSchool(ids);
        
        schoolService.updateSchoolTeacherNumBySchoolId(schoolId);

        
        return RestResult.ok();
    }
    
    /**
     * 导入教师
     *
	 * @apiGroup teacher
	 * @api {post} /teacher/importteacher 导入教师
	 * @apiVersion 1.0.0
	 * @apiName importTeacher
	 *
	 * @apiParam {MultipartFile} file 教师excel文件
	 * @apiParam {Long} schoolId 学校id
	 * @apiParam {HttpServletRequest} request 
	 *
	 * @apiSuccessExample Success-Response:
	 * HTTP/1.1 200
		{
		    "code": 200,
		    "msg": "success",
		    "data": {
		        "statusinfo": "success"
		    }
		}
	 *
	 *
	 */
	@RequestMapping(value = "importteacher", name = "导入教师", method = RequestMethod.POST)
	@PreAuthorize("hasAuthority('/teacher/importteacher')")
	public RestResult importTeacher(MultipartFile file, 
			@RequestParam(value = "schoolId") Long schoolId, 
										HttpServletRequest request) throws Exception {
		
		Map<String, Object> result = userService.importTeacher(file, schoolId, request);

		return RestResult.ok(result);
		
	}

 

}
